import json
import time
from .config import SENSOR_CONFIG

class SensorHandler:
    def __init__(self, serial_connection):
        self.serial = serial_connection
        self.sensor_data = {}
        self.running = False
        self.thread = None

    def start(self):
        """启动传感器读取线程"""
        self.running = True
        self.thread = threading.Thread(target=self._read_loop, daemon=True)
        self.thread.start()

    def stop(self):
        """停止传感器读取线程"""
        self.running = False
        if self.thread:
            self.thread.join()

    def _read_loop(self):
        """传感器数据读取循环"""
        while self.running:
            if self.serial.in_waiting:
                self._process_serial_data()
            time.sleep(SENSOR_CONFIG['read_interval'])

    def _process_serial_data(self):
        """处理串口接收到的传感器数据"""
        try:
            raw_data = self.serial.readline().decode().strip()
            if raw_data.startswith('{') and raw_data.endswith('}'):
                self.sensor_data = json.loads(raw_data)
        except json.JSONDecodeError:
            # 记录JSON解析错误
            pass
        except Exception as e:
            # 记录其他异常
            pass

    def get_latest_data(self):
        """获取最新的传感器数据"""
        return self.sensor_data.copy()